package com.share.payment.api;

import cn.hutool.core.util.ObjectUtil;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.web.controller.BaseController;
import com.share.common.core.web.domain.AjaxResult;
import com.share.common.security.annotation.RequiresLogin;
import com.share.payment.domain.CreateWxPaymentForm;
import com.share.payment.domain.WxPrepayVo;
import com.share.payment.service.IWxService;
import com.share.payment.service.impl.PaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/10/25 上午8:59
 */
@Tag(name = "微信支付接口")
@RestController
@RequestMapping("/wxPay")
@Slf4j
@RequiredArgsConstructor
public class WxPayApiController extends BaseController {

    private final IWxService wxService;
    private final PaymentInfoService paymentInfoService;

    @Operation(summary = "微信下单")
    @PostMapping("/createWxPayment")
    public AjaxResult createWxPayment(@RequestBody CreateWxPaymentForm createWxPaymentForm) {
        WxPrepayVo wxPrepayVo = wxService.createWxPayment(createWxPaymentForm);
        return success(wxPrepayVo);
    }


    @Operation(summary = "支付状态查询")
    @GetMapping("/queryPayStatus/{orderNo}")
    public AjaxResult queryPayStatus(@PathVariable String orderNo) {
        //根据订单编号调用微信服务接口，查询支付相关状态信息
        WxPayOrderQueryResult wxPayOrderQueryResult = wxService.queryPayStatus(orderNo);
        if (!ObjectUtils.isEmpty(wxPayOrderQueryResult) &&
                WxPayConstants.WxpayTradeStatus.SUCCESS.equals(wxPayOrderQueryResult.getTradeState())) {
            paymentInfoService.updatePaymentStatus(wxPayOrderQueryResult);
            return success(true);
        }
        return success(false);
    }


}
